<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
  *Catatan :
  *Library yang harus disimpan pada autoload : Session
  *Helper yang harus disimpan pada autoload : Url
  */
class Authniter{
    var $CI;
    
    function Authniter(){
        $this->CI =& get_instance();
    }
    
    function filter(){
        $uri = $this->CI->uri->uri_string();
        $rule= $this->getRule();
                    
        $uri = empty($uri)?"/":$uri;
        if($this->_areGroupsAllowed($uri,$rule)){
            
        }else{
            $this->CI->session->set_flashdata('notification',"Maaf halaman tidak ditemukan");
            redirect('/');

        }
    }
    
    function isLogged(){
        return ((int)$this->CI->session->userdata('authniter_logged')==1);
    }
    
    function logout(){
        $this->destroyData();
        $this->CI->session->set_flashdata('notification',"Anda telah loggout");
        redirect('/');
    }
    
    function login($username='',$password='',$url='/'){
        
        if($this->isLogged()){
            $this->CI->session->set_flashdata('notification',"Anda telah loggin sebelumnya");
            redirect('/');
        }else{
            $qry = "SELECT * FROM authniter_users WHERE CONCAT(login,'@',password)=CONCAT(?,'@',md5(?))";
            $data = $this->CI->db->query($qry,array($username,$password));
            if($data->num_rows() > 0 ){
                $user = $data->row();
				//print_r($data->row_array());
                $groups_id = $this->_getListGroups($user->id);
                $groups_name = $this->_getListGroupsName($groups_id);
                //$rule = $this->_getListUserRule($groups_id); 
                
                $listUserData = Array(
                    'authniter_logged'=>1,
                    'authniter_profil_id'=>$user->profil_id,
                    'authniter_user_id'=>$user->id,
                    'authniter_groups_id'=>$groups_id,
                    'authniter_groups_name'=>$groups_name,
                    'authniter_username'=>$user->login
                );
                
                $this->CI->session->set_userdata($listUserData);     
                redirect('/');
                
            }else{
                $this->CI->session->set_flashdata('notification',"Maaf username dan password Anda tidak cocok" );
                redirect($url);
            }
        }
        
    }
    
    function destroyData(){
         $listUserData = Array(
                    'authniter_logged'=>'',
                    'authniter_profil_id'=>'',
                    'authniter_user_id'=>'',
                    'authniter_groups_id'=>'',
                    'authniter_groups_name'=>'',
                    'authniter_username'=>'',
                    'authniter_user_rule'=>''
                );
        $this->CI->session->unset_userdata($listUserData);
    }
    
    function getUserId(){
        return $this->CI->session->userdata('authniter_user_id');
    }
    
    function getUsername(){
        return $this->CI->session->userdata('authniter_username');
    }

    function getProfilId(){
        return $this->CI->session->userdata('authniter_profil_id');
    }
    
    function isMemberOf($group_id=-1){
      $listGroup = $this->getGroupsId();
      if(is_array($listGroup)){
        return in_array($group_id, $listGroup);
      }else{
        return 0;
      }
    }
    
    function getGroupsId(){
        return $this->CI->session->userdata('authniter_groups_id');
    }
    
    function getGroupsName(){
        return $this->CI->session->userdata('authniter_groups_name');
    }
    
    function getRule(){
        //return $this->CI->session->userdata('authniter_user_rule');
        $groups_id = $this->getGroupsId();
        if(empty($groups_id))
            $groups_id = array(0);
            
        return $this->_getListUserRule($groups_id);
    }
    
    function _getListGroups($userid=-1){
        $qry = "SELECT agu.group_id FROM authniter_groups_users agu WHERE agu.user_id=?";
        $data = $this->CI->db->query($qry,array($userid));
        $lstGroup = array(0);
        foreach($data->result() as $group)
            $lstGroup[] = $group->group_id;
        return $lstGroup;
    }
    
    function _getListGroupsName($list_groups=array()){
        $str = implode(',',$list_groups);
        $qry = "SELECT g.name FROM authniter_groups g WHERE g.id in ($str)";
        $data = $this->CI->db->query($qry);
        $lstGroupName = array();
        foreach($data->result() as $group)
            $lstGroupName[] = $group->name;
        return $lstGroupName;
    }

    function _getListUserRule($list_groups=array()){
        $str = implode(',',$list_groups);
        $qry = "SELECT r.action,r.permission FROM authniter_rules r WHERE r.group_id in ($str) ORDER BY `order`";
        $data = $this->CI->db->query($qry);
        
        $rule = $data->result_array();
        foreach($rule as $id=>$detail){
            $rule[$id]['action'] = str_replace(array('/','*',' or '), array('\/', '.*','|'), $detail['action']);
        }
        
        return $rule;
    }
    // Function to check the access for the controller / action
    function _areGroupsAllowed($url = "", $rules) { // $checkStr: "/name/action/" $group_ids: check again thess groups
        $allow = false;
        foreach( $rules as $data ) {
        if(preg_match("/^({$data['action']})$/i", $url, $matches)) {
            $allow = $data['permission'];
            if ($allow == 'Deny')
                $allow = false;
            else
                $allow = true;
            }
        }
        return $allow;
    }
    
    function isAllowed($url=""){
        $rule = $this->getRule();
        return $this->_areGroupsAllowed($url , $rule);
    }
}
?>